package com.huluobo.a2201mvvm_imdemo.net;

import java.sql.Time;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by LC on 2024/4/8.
 * 网络请求工具类,使用单例模式,
 */
public class RetrofitManager {
    //    private static RetrofitManager retrofitManager=new RetrofitManager();//饿汉模式
    private static RetrofitManager retrofitManager;

    //单例模式的核心,私有化构造函数,在外部使用的时候只要new一次,就会出现一个新的对象,要保证单例的话,不能让外部去new出实例,只能提供
    private RetrofitManager() {

    }

    //对外提供一个暴露的实例
    public static RetrofitManager getInstance() {
        if (retrofitManager == null) {
            retrofitManager = new RetrofitManager();
        }
        return retrofitManager;
    }

    private Retrofit retrofit;

    public Retrofit getRetrofit() {
        if (retrofit == null) {
            retrofit = createRetrofit();
        }
        return retrofit;
    }

    //创建retrofit网络请求工具
    private Retrofit createRetrofit() {
        //okHttp
        OkHttpClient.Builder okhttpClient = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY));

        //Retrofit
        Retrofit.Builder retrofitBuilder = new Retrofit.Builder()
                .client(okhttpClient.build())
                .baseUrl("http://10.161.9.80:7012")
                .addConverterFactory(GsonConverterFactory.create()) //能直接把请求返回的数据转换为jsonBean
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create());//只要负责线程切换

        return retrofitBuilder.build();
    }

}
